package com.xiaomi.eco.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaomi.eco.dal.entity.*;
import com.xiaomi.eco.dal.res.TaskListRes;
import com.xiaomi.eco.mapper.EcoCompanyTaskListEntityMapper;
import com.xiaomi.eco.mapper.EcoCompanyWebMappingEntityMapper;
import com.xiaomi.eco.mapper.EcoMethodDimensionEntityMapper;
import com.xiaomi.eco.service.*;
import com.xiaomi.eco.utils.EcoRobotMethod;
import com.xiaomi.eco.utils.EcoServiceQualityAlarm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.*;
import java.time.temporal.ChronoUnit;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@Slf4j
public class EcoCompanyTaskListEntityServiceImpl extends
        ServiceImpl<EcoCompanyTaskListEntityMapper, EcoCompanyTaskListEntity> implements EcoCompanyTaskListEntityService {

    StringBuilder sb = new StringBuilder();
    @Autowired
    private RestTemplate restTemplate;

    private static LambdaUpdateWrapper<EcoCompanyWebMappingEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();

    @Autowired
    private EcoMethodDimensionEntityService ecoMethodDimensionService;

    @Autowired
    private EcoCompanyTaskListEntityMapper ecoCompanyTaskListEntityMapper;

    @Autowired
    private EcoCompanyWhiteListEntityService ecoCompanyWhiteListEntityService;

    @Autowired
    private EcoCompanyWebMappingEntityMapper ecoCompanyWebMappingEntityMapper;

    @Autowired
    private EcoCompanyWebMappingEntityService ecoCompanyWebMappingEntityService;
    @Autowired
    private TbEcoApplicationCompanyEntityService tbEcoApplicationCompanyEntityService;

    private static ObjectMapper objectMapper = new ObjectMapper();
    LambdaQueryWrapper<EcoCompanyTaskListEntity> queryWrapper = new LambdaQueryWrapper<>();

    @Autowired
    private EcoMethodDimensionEntityMapper ecoMethodDimensionEntityMapper;

    @Override
    public void insertEcoCompanyTaskListService() {
        List<EcoMethodDimensionEntity> ecoMethodDimensionEntityList = ecoCompanyTaskListEntityMapper.selectRepeat();//查询出最近7天内最新时间有问题的接口
        for (EcoMethodDimensionEntity ecoMethodDimensionEntity : ecoMethodDimensionEntityList) {
            boolean flag = whilteJudge(ecoMethodDimensionEntity.getHttpMethodName());
            if (!flag) {
                //白名单过滤
                continue;
            }
            String futureTimestamp = createEndTime();
            String takesTimeP99 = ecoMethodDimensionEntity.getTakesTimeP99();
            String takesTimeP95 = ecoMethodDimensionEntity.getTakesTimeP95();
            String methodAvailabilityStr = ecoMethodDimensionEntity.getMethodAvailability();
            String principalPhone = getprincipalPhone(ecoMethodDimensionEntity.getApplicationId());
            String principalCompany = getPrincipalCompany(ecoMethodDimensionEntity.getApplicationId());
            String principalName = getPrincipalName(ecoMethodDimensionEntity.getApplicationId());


            String userId = getUserId(ecoMethodDimensionEntity.getApplicationId(), EcoServiceQualityAlarm.APPLICATION);
            if (userId.isEmpty() || userId.equals("")) {
                continue;
            }


            EcoCompanyTaskListEntity ecoCompanyTaskListEntity = EcoCompanyTaskListEntity.builder()
                    .taskName(null)
                    .methodName(ecoMethodDimensionEntity.getHttpMethodName())
                    .taskTimeP95(ecoMethodDimensionEntity.getTakesTimeP95() == null ? "0" : new BigDecimal(ecoMethodDimensionEntity.getTakesTimeP95()).setScale(2, RoundingMode.HALF_UP).toString())
                    .taskTimeP99(ecoMethodDimensionEntity.getTakesTimeP99() == null ? "0" : new BigDecimal(ecoMethodDimensionEntity.getTakesTimeP99()).setScale(2, RoundingMode.HALF_UP).toString())
                    .errorNum(ecoMethodDimensionEntity.getNumberOfErrors())
                    .taskStatus(EcoServiceQualityAlarm.COMPLETEING)
                    .principalPhone(principalPhone)
                    .principalCompany(principalCompany)
                    .createTime(LocalDate.now().toString().replaceAll("-", ""))
                    .updateTime(LocalDate.now().toString().replaceAll("-", ""))
                    .endTime(futureTimestamp.replaceAll("-", ""))
                    .completeTime(null)
                    .taskUrl(null)
                    .taskId(null)
                    .taskType(null)
                    .methodType(ecoMethodDimensionEntity.getHttpMethodType())
                    .principalName(principalName)
                    .serverZone(ecoMethodDimensionEntity.getServerZone())
                    .build();
            String summary = "";
            double availabilityResult = 0;
            if (methodAvailabilityStr != null && Double.valueOf(methodAvailabilityStr.replaceAll("%", "")) < EcoServiceQualityAlarm.availabilityNum) {
                summary = sb.append(EcoServiceQualityAlarm.availabilityIsNotCommom).append(ecoCompanyTaskListEntity.getMethodName()).toString();
                sb.setLength(0);
                ecoCompanyTaskListEntity.setTaskType(EcoServiceQualityAlarm.availabilityIsNotUpToPar);
            } else if (methodAvailabilityStr == null && ecoMethodDimensionEntity.getNumberOfErrors() != null
                    && ecoMethodDimensionEntity.getTotalCalls() != null) {
                availabilityResult = (ecoMethodDimensionEntity.getTotalCalls() - Double.valueOf(ecoMethodDimensionEntity.getNumberOfErrors())) / ecoMethodDimensionEntity.getTotalCalls();
                if (availabilityResult < 0.9995) {
                    summary = sb.append(EcoServiceQualityAlarm.availabilityIsNotCommom).append(ecoCompanyTaskListEntity.getMethodName()).toString();
                    sb.setLength(0);
                    ecoCompanyTaskListEntity.setTaskType(EcoServiceQualityAlarm.availabilityIsNotUpToPar);
                }
            } else if (ecoMethodDimensionEntity.getNumberOfErrors() != null && Double.valueOf(ecoMethodDimensionEntity.getNumberOfErrors()) > 50) {
                summary = sb.append(EcoServiceQualityAlarm.availabilityIsNotCommom).append(ecoCompanyTaskListEntity.getMethodName()).toString();
                sb.setLength(0);
                ecoCompanyTaskListEntity.setTaskType(EcoServiceQualityAlarm.availabilityIsNotUpToPar);
            } else if (takesTimeP95 != null && Double.valueOf(takesTimeP95) > EcoServiceQualityAlarm.timeOnsumingP95) {
                summary = sb.append(EcoServiceQualityAlarm.slowDownCommom).append(ecoCompanyTaskListEntity.getMethodName()).toString();
                sb.setLength(0);
                ecoCompanyTaskListEntity.setTaskType(EcoServiceQualityAlarm.slowInterface);
            } else if (takesTimeP99 != null && Double.valueOf(takesTimeP99) > EcoServiceQualityAlarm.timeOnsumingP99) {
                summary = sb.append(EcoServiceQualityAlarm.slowDownCommom).append(ecoCompanyTaskListEntity.getMethodName()).toString();
                sb.setLength(0);
                ecoCompanyTaskListEntity.setTaskType(EcoServiceQualityAlarm.slowInterface);
            }

            //查询条件
            queryWrapper.clear();
            if (ecoMethodDimensionEntity.getHttpMethodType() == null) {
                queryWrapper.eq(EcoCompanyTaskListEntity::getMethodName, ecoCompanyTaskListEntity.getMethodName());
                queryWrapper.eq(EcoCompanyTaskListEntity::getTaskStatus, EcoServiceQualityAlarm.COMPLETEING)
                        .eq(EcoCompanyTaskListEntity::getPrincipalPhone, principalPhone)
                        .eq(EcoCompanyTaskListEntity::getPrincipalName, principalName)
                        .eq(EcoCompanyTaskListEntity::getPrincipalCompany, principalCompany)
                        .eq(EcoCompanyTaskListEntity::getServerZone, ecoCompanyTaskListEntity.getServerZone());
                queryWrapper.orderByDesc(EcoCompanyTaskListEntity::getCreateTime).last("LIMIT 1");
            } else {
                queryWrapper.eq(EcoCompanyTaskListEntity::getMethodName, ecoCompanyTaskListEntity.getMethodName());
                queryWrapper.eq(EcoCompanyTaskListEntity::getTaskStatus, EcoServiceQualityAlarm.COMPLETEING)
                        .eq(EcoCompanyTaskListEntity::getMethodType, ecoCompanyTaskListEntity.getMethodType())
                        .eq(EcoCompanyTaskListEntity::getPrincipalPhone, principalPhone)
                        .eq(EcoCompanyTaskListEntity::getPrincipalName, principalName)
                        .eq(EcoCompanyTaskListEntity::getPrincipalCompany, principalCompany)
                        .eq(EcoCompanyTaskListEntity::getServerZone, ecoCompanyTaskListEntity.getServerZone());
                queryWrapper.orderByDesc(EcoCompanyTaskListEntity::getCreateTime).last("LIMIT 1");
            }

            List<EcoCompanyTaskListEntity> ecoCompanyTaskListEntityList = ecoCompanyTaskListEntityMapper.selectList(queryWrapper);
            //更新
            if (CollectionUtils.isNotEmpty(ecoCompanyTaskListEntityList)) {
                ecoCompanyTaskListEntity.setId(ecoCompanyTaskListEntityList.get(0).getId());
                ecoCompanyTaskListEntity.setTaskId(ecoCompanyTaskListEntityList.get(0).getTaskId());
                ecoCompanyTaskListEntity.setTaskUrl(ecoCompanyTaskListEntityList.get(0).getTaskUrl());
                ecoCompanyTaskListEntity.setTaskName(ecoCompanyTaskListEntityList.get(0).getTaskName());
                ecoCompanyTaskListEntity.setTaskTimeP95(ecoMethodDimensionEntity.getTakesTimeP95() == null ? "0" : new BigDecimal(ecoMethodDimensionEntity.getTakesTimeP95()).setScale(2, RoundingMode.HALF_UP).toString());
                ecoCompanyTaskListEntity.setTaskTimeP99(ecoMethodDimensionEntity.getTakesTimeP99() == null ? "0" : new BigDecimal(ecoMethodDimensionEntity.getTakesTimeP99()).setScale(2, RoundingMode.HALF_UP).toString());
                ecoCompanyTaskListEntity.setErrorNum(ecoMethodDimensionEntity.getNumberOfErrors());
                ecoCompanyTaskListEntity.setServerZone(ecoMethodDimensionEntity.getServerZone());
                update(ecoCompanyTaskListEntity, queryWrapper);
            } else if (CollectionUtils.isEmpty(ecoCompanyTaskListEntityList) || (CollectionUtils.isNotEmpty(ecoCompanyTaskListEntityList) && ecoCompanyTaskListEntityList.get(0).getTaskStatus().equals(EcoServiceQualityAlarm.COMPLETED))) {
                //如果在任务表里存在且状态是完成 或者 如果是任务表里不存在
                if (summary.isEmpty() || summary == null) {
                    System.out.println("summary is null:   " + ecoMethodDimensionEntity);
                    continue;
                }
                log.info("传入前的userId:" + userId);

                EcoCompanyWebMappingEntity ecoCompanyWebMappingEntity = ecoCompanyWebMappingEntityService.getOne(
                        new LambdaQueryWrapper<EcoCompanyWebMappingEntity>().eq(EcoCompanyWebMappingEntity::getPrinciPhone, principalPhone).eq(
                                EcoCompanyWebMappingEntity::getPrincipalName, principalName
                        ).eq(EcoCompanyWebMappingEntity::getCompanyName, principalCompany));
                if ((ecoCompanyWebMappingEntity.getTasklistId().isEmpty() || ecoCompanyWebMappingEntity.getTasklistId().equals("")) &&
                        (ecoCompanyWebMappingEntity.getSectionId().isEmpty() || ecoCompanyWebMappingEntity.getSectionId().equals(""))) {
                    //如果为空,创建分组
                    String taskListSection = createTaskListSection(ecoCompanyWebMappingEntity, ecoMethodDimensionEntity.getIsSelfStudy());
                    if (taskListSection.equals("") || taskListSection.isEmpty()) {
                        continue;
                    }
                }
                String createGuid = createTask(ecoCompanyTaskListEntity, userId, futureTimestamp, summary, ecoCompanyWebMappingEntity.getTasklistId(), ecoCompanyWebMappingEntity.getSectionId(), ecoMethodDimensionEntity.getIsSelfStudy());
                String getTaskUrl = getTask(createGuid, ecoMethodDimensionEntity.getIsSelfStudy());
                ecoCompanyTaskListEntity.setTaskName(summary);
                ecoCompanyTaskListEntity.setTaskUrl(getTaskUrl);
                ecoCompanyTaskListEntity.setTaskId(createGuid);
                ecoCompanyTaskListEntityMapper.insert(ecoCompanyTaskListEntity);
            }
        }
    }

    //获取生态链公司负责人
    private String getPrincipalName(String applicationId) {
        List<TbEcoApplicationCompanyEntity> tbEcoApplicationCompanyEntityList = tbEcoApplicationCompanyEntityService.list();
        Map<String, TbEcoApplicationCompanyEntity> applicationMap = tbEcoApplicationCompanyEntityList.stream().collect(Collectors.toMap(TbEcoApplicationCompanyEntity::getApplicationId, Function.identity(), (v1, v2) -> v2));
        TbEcoApplicationCompanyEntity applicationEntity = applicationMap.get(applicationId);
        if (applicationEntity == null) {
            return "";
        }
        List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
        Map<String, EcoCompanyWebMappingEntity> companyWebMappingMap = ecoCompanyWebMappingEntityList.stream().collect(Collectors.toMap(EcoCompanyWebMappingEntity::getCompanyName, Function.identity()));
        if (companyWebMappingMap == null) {
            return "";
        }
        EcoCompanyWebMappingEntity companyEntity = companyWebMappingMap.get(applicationEntity.getCompanyName());
        if (companyEntity == null) {
            return "";
        }
        String principalName = companyEntity.getPrincipalName();
        return principalName;
    }

    //获取生态链公司名称
    private String getPrincipalCompany(String applicationId) {
        List<TbEcoApplicationCompanyEntity> tbEcoApplicationCompanyEntityList = tbEcoApplicationCompanyEntityService.list();
        Map<String, TbEcoApplicationCompanyEntity> applicationMap = tbEcoApplicationCompanyEntityList.stream().collect(Collectors.toMap(TbEcoApplicationCompanyEntity::getApplicationId, Function.identity(), (v1, v2) -> v2));
        TbEcoApplicationCompanyEntity applicationEntity = applicationMap.get(applicationId);
        if (applicationEntity == null) {
            return "";
        }
        List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
        Map<String, EcoCompanyWebMappingEntity> companyWebMappingMap = ecoCompanyWebMappingEntityList.stream().collect(Collectors.toMap(EcoCompanyWebMappingEntity::getCompanyName, Function.identity()));
        if (companyWebMappingMap == null) {
            return "";
        }
        EcoCompanyWebMappingEntity companyEntity = companyWebMappingMap.get(applicationEntity.getCompanyName());
        if (companyEntity == null) {
            return "";
        }
        String principalCompany = companyEntity.getCompanyName();
        return principalCompany;
    }

    //获取生态链公司负责人手机号
    private String getprincipalPhone(String applicationId) {
        List<TbEcoApplicationCompanyEntity> tbEcoApplicationCompanyEntityList = tbEcoApplicationCompanyEntityService.list();
        Map<String, TbEcoApplicationCompanyEntity> applicationMap = tbEcoApplicationCompanyEntityList.stream().collect(Collectors.toMap(TbEcoApplicationCompanyEntity::getApplicationId, Function.identity(), (v1, v2) -> v2));
        TbEcoApplicationCompanyEntity applicationEntity = applicationMap.get(applicationId);
        if (applicationEntity == null) {
            return "";
        }
        List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
        Map<String, EcoCompanyWebMappingEntity> companyWebMappingMap = ecoCompanyWebMappingEntityList.stream().collect(Collectors.toMap(EcoCompanyWebMappingEntity::getCompanyName, Function.identity()));
        if (companyWebMappingMap == null) {
            return "";
        }
        EcoCompanyWebMappingEntity companyEntity = companyWebMappingMap.get(applicationEntity.getCompanyName());
        if (companyEntity == null) {
            return "";
        }
        String principalPhone = companyEntity.getPrinciPhone();

        return principalPhone;
    }


    //白名单过滤
    public boolean whilteJudge(String httpMethod) {
        List<EcoCompanyWhiteListEntity> ecoCompanyWhiteListEntityList = ecoCompanyWhiteListEntityService.list();
        if (CollectionUtils.isEmpty(ecoCompanyWhiteListEntityList)) {
            return true;
        }
        for (EcoCompanyWhiteListEntity ecoCompanyWhiteListEntity : ecoCompanyWhiteListEntityList) {
            if (ecoCompanyWhiteListEntity.getHttpMethod().equals(httpMethod)) {
                //如果遇到不需要优化的接口
                return false;
            }
        }
        return true;
    }

    @Value("${Feishu2.appId}")
    private String appId2;

    @Value("${Feishu2.appSecret}")
    private String appSecret2;

    @Value("${Feishu.appId}")
    private String appId;

    @Value("${Feishu.appSecret}")
    private String appSecret;


    public String getTenantAccessToken(Long isSelfStudy) {
        String tenantAccessToken = "";
        if (isSelfStudy == 0) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String innerRequestTenantAccessToken = String.format(EcoServiceQualityAlarm.requestTenantAccessToken, appId2, appSecret2);
            String innerTenantAccessTokenResponse = EcoRobotMethod.postForObject(EcoServiceQualityAlarm.tenantAccessTokenUrl, innerRequestTenantAccessToken);
            JsonNode innerTenantAccessTokenResponJsonNode = null;
            System.out.println("走自研任务创建的机器人: "+innerTenantAccessTokenResponse);
            try {
                innerTenantAccessTokenResponJsonNode = objectMapper.readTree(innerTenantAccessTokenResponse);
            } catch (JsonProcessingException e) {
                log.error("获取内部机器人json解析失败: {}", innerTenantAccessTokenResponJsonNode);
            }
            tenantAccessToken = innerTenantAccessTokenResponJsonNode.get(EcoServiceQualityAlarm.tenantAccessToken).asText();
        } else if (isSelfStudy == 1) {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            String externalRequestTenantAccessToken = String.format(EcoServiceQualityAlarm.requestTenantAccessToken, appId, appSecret);
            String externalTenantAccessTokenResponse = EcoRobotMethod.postForObject(EcoServiceQualityAlarm.tenantAccessTokenUrl, externalRequestTenantAccessToken);
            System.out.println("走外部创建任务创建的机器人: "+externalTenantAccessTokenResponse);
            JsonNode externalTenantAccessTokenResponJsonNode = null;
            try {
                externalTenantAccessTokenResponJsonNode = objectMapper.readTree(externalTenantAccessTokenResponse);
            } catch (JsonProcessingException e) {
                log.error("获取外部机器人json解析失败: {}", externalTenantAccessTokenResponse);
            }
            tenantAccessToken = externalTenantAccessTokenResponJsonNode.get(EcoServiceQualityAlarm.tenantAccessToken).asText();
        }


        return tenantAccessToken;
    }

    //获取userId
    public String getUserId(String userInfo, String Type) {
        String userId = "";
        if (Type.equals(EcoServiceQualityAlarm.APPLICATION)) {
            List<TbEcoApplicationCompanyEntity> tbEcoApplicationCompanyEntityList = tbEcoApplicationCompanyEntityService.list();
            //比如说有个叫网关的数据
            Map<String, TbEcoApplicationCompanyEntity> applicationMap = tbEcoApplicationCompanyEntityList.stream().collect(Collectors.toMap(TbEcoApplicationCompanyEntity::getApplicationId, Function.identity(), (v1, v2) -> v2));
            TbEcoApplicationCompanyEntity applicationEntity = applicationMap.get(userInfo);
            if (applicationEntity == null) {
                log.info("在tbEcoApplicationCompany表里查询不到对应的applicaTionId");
                return "";
            }
            List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
            Map<String, EcoCompanyWebMappingEntity> companyWebMappingMap = ecoCompanyWebMappingEntityList.stream().collect(Collectors.toMap(EcoCompanyWebMappingEntity::getCompanyName, Function.identity()));
            if (companyWebMappingMap == null) {
                log.info("查询ecoCompanyWebMapping表为null");
                return "";
            }
            EcoCompanyWebMappingEntity companyEntity = companyWebMappingMap.get(applicationEntity.getCompanyName());
            if (companyEntity == null) {
                log.info("根据ecoCompanyWebMapping表查询具体公司数据为null");
                return "";
            }
            userId = companyEntity.getAccount();
        } else if (Type.equals(EcoServiceQualityAlarm.principalPhone)) {
            List<EcoCompanyWebMappingEntity> ecoCompanyWebMappingEntityList = ecoCompanyWebMappingEntityService.list();
            for (EcoCompanyWebMappingEntity ecoCompanyWebMappingEntity : ecoCompanyWebMappingEntityList) {
                if (ecoCompanyWebMappingEntity.getPrinciPhone().equals(userInfo)) {
                    userId = ecoCompanyWebMappingEntity.getAccount();
                }
            }
        }
        if (userId.equals("")) {
            log.info("根据ecoCompanyWebMapping表查询userid为null");
        }

        return userId;
    }





    //获取任务截止时间方法-15天后
    public String createEndTime() {
        // 获取当前日期
        LocalDate today = LocalDate.now();
        LocalDate inFifteenDays = null;
        List<EcoCompanyWhiteListEntity> ecoCompanyWhiteListEntityList = ecoCompanyWhiteListEntityService.list();
        for (EcoCompanyWhiteListEntity ecoCompanyWhiteListEntity : ecoCompanyWhiteListEntityList) {
            if (ecoCompanyWhiteListEntity.getCompanyId().isEmpty() && ecoCompanyWhiteListEntity.getCompanyName().isEmpty()
                    && ecoCompanyWhiteListEntity.getHttpMethod().isEmpty()) {
                // 将今天的日期加上15天
                inFifteenDays = today.plus(ecoCompanyWhiteListEntity.getDays(), ChronoUnit.DAYS);
            }
        }

        return inFifteenDays.toString();
    }

    //创建任务
    public String createTask(EcoCompanyTaskListEntity ecoCompanyTaskListEntity, String userId, String futureTime, String summary, String taskId, String sectionId, Long isSelfStudy) {
        LocalDate localDate = LocalDate.parse(futureTime);
        ZonedDateTime zonedDateTime = localDate.atStartOfDay(ZoneId.systemDefault());
        String futureTimestamp = String.valueOf(zonedDateTime.toInstant().toEpochMilli());
        String uuid = UUID.randomUUID().toString();
        String description = "该任务属于: " + ecoCompanyTaskListEntity.getTaskType() + "   p95值: " + ecoCompanyTaskListEntity.getTaskTimeP95() + "   p99值: " + ecoCompanyTaskListEntity.getTaskTimeP99() + "   错误数: " + (ecoCompanyTaskListEntity.getErrorNum() == null ? 0 : ecoCompanyTaskListEntity.getErrorNum()) + "   机房: " + (ecoCompanyTaskListEntity.getServerZone() == null ? "" : ecoCompanyTaskListEntity.getServerZone());
        log.info("createTask里的userId: " + userId);
        String requestTak = String.format(EcoServiceQualityAlarm.creqateTaskParam, summary, description, futureTimestamp, userId, userId, taskId, sectionId, uuid, String.valueOf(System.currentTimeMillis()));
        log.info("requestTak:  " + requestTak);
        String createTaskResponse = "";
        if (isSelfStudy == 0) {
            //自研任务
            createTaskResponse = EcoRobotMethod.insertTaskFeishu(getTenantAccessToken(isSelfStudy), requestTak);
        } else if (isSelfStudy == 1) {
            createTaskResponse = EcoRobotMethod.insertTaskFeishu(getTenantAccessToken(isSelfStudy), requestTak);
        }
        JsonNode createTaskNode = null;
        if (createTaskResponse.isEmpty()) {
            log.info("createTaskResponse is null ");
            return "";
        }
        try {
            createTaskNode = objectMapper.readTree(createTaskResponse);
        } catch (JsonProcessingException e) {
            log.error("json解析失败: {}", createTaskResponse);
        }
        if (createTaskNode == null) {
            log.info("createTaskNode is nuill");
            return "";
        }
        int createCode = createTaskNode.get(EcoServiceQualityAlarm.CODE).asInt();

        String createGuid = "";
        if (createCode == 0) {
            JsonNode dataNode = createTaskNode.get(EcoServiceQualityAlarm.DATA);
            log.info("createTaskNode : {},dataNode: {}", createTaskNode, dataNode);
            if (dataNode == null) {
                log.info("dataNode is nuill");
                return "";
            }
            JsonNode taskNode = dataNode.get(EcoServiceQualityAlarm.TASK);
            createGuid = taskNode.get(EcoServiceQualityAlarm.GUID).asText();
        }
        return createGuid;
    }

    //获得任务详情
    public String getTask(String createGuid, Long isSelfStudy) {
        JsonNode searchNode = null;
        String searchBody = EcoRobotMethod.selectTaskFeiShu(getTenantAccessToken(isSelfStudy), createGuid);
        if (searchBody == null) {
            log.info("searchBody is null");
            return "";
        }
        try {
            searchNode = objectMapper.readTree(searchBody);
        } catch (JsonProcessingException e) {
            log.error("json解析失败,json为: {}", searchBody);
        }
        if (searchNode == null) {
            log.info("searchNode is null");
            return "";
        }

        int searchCode = searchNode.get(EcoServiceQualityAlarm.CODE).asInt();
        if (searchCode == 0) {
            JsonNode searchTaskNode = searchNode.get(EcoServiceQualityAlarm.DATA);
            log.info("searchTaskNode : {}", searchTaskNode);
            if (searchTaskNode == null) {
                log.info("searchTaskNode is null");
                return "";
            }
            JsonNode searchTaskDataNode = searchTaskNode.get(EcoServiceQualityAlarm.TASK);
            String url = searchTaskDataNode.get(EcoServiceQualityAlarm.URL).asText();
            return url;
        } else {
            return "";
        }
    }

    public String createTaskListSection(EcoCompanyWebMappingEntity ecoCompanyWebMappingEntity, Long isSelfStudy) {
        String taskListGuid = "";
        String tasklistsUrl = "https://open.f.mioffice.cn/open-apis/task/v2/tasklists?user_id_type=user_id";
        String client_token = ecoCompanyWebMappingEntity.getAccount() + "shengtailian";
        String tasklistParam = "{\n" +
                "    \"name\": \"小米服务质量改善\",\n" +
                "    \"client_token\": \"" + client_token + "\",\n" +
                "    \"members\": [\n" +
                "        {\n" +
                "            \"id\": \"" + ecoCompanyWebMappingEntity.getAccount() + "\",\n" +
                "            \"type\": \"user\",\n" +
                "            \"role\": \"editor\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + getTenantAccessToken(isSelfStudy));
        HttpEntity<String> taskListEntity = new HttpEntity<>(tasklistParam, headers);
        String tasklistResponse = "";
        try {
            tasklistResponse = restTemplate.postForObject(tasklistsUrl, taskListEntity, String.class);
        } catch (Exception e) {
            log.info("创建清单失败，请求体为: {}", tasklistParam);
        }
        if (tasklistResponse.isEmpty() || tasklistResponse.equals("")) {
            log.info("创建清单返回参数为空: {}", tasklistResponse);
            return "";
        }
        try {
            TaskListRes taskListRes = objectMapper.readValue(tasklistResponse, TaskListRes.class);
            if (taskListRes.getCode() == 0 && taskListRes.getMsg().equals("success")) {
                taskListGuid = taskListRes.getData().getTaskList().getGuid();
                System.out.println(taskListGuid);
            } else {
                log.info("解析创建清单的json失败: {}", taskListRes.toString());
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        String sectionUrl = "https://open.f.mioffice.cn/open-apis/task/v2/sections?user_id_type=user_id";
        String sectionGuid = "";
        String sectiionParam = "{\n" +
                "    \"name\": \"小米服务质量改善\",\n" +
                "    \"resource_type\": \"tasklist\",\n" +
                "    \"resource_id\": \"" + taskListGuid + "\"\n" +
                "}";
        headers.clear();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + getTenantAccessToken(isSelfStudy));
        HttpEntity<String> sectionEntity = new HttpEntity<>(sectiionParam, headers);
        String createTaskResponse = restTemplate.postForObject(sectionUrl, sectionEntity, String.class);
        if (createTaskResponse.isEmpty() || createTaskResponse.equals("")) {
            log.info("创建清单分组返回参数为空: {}", createTaskResponse);
            return "";
        }

        try {
            JsonNode jsonNode1 = objectMapper.readTree(createTaskResponse);
            int code = jsonNode1.get("code").asInt();
            String msg = jsonNode1.get("msg").asText();
            if (code == 0 && msg.equals("success")) {
                sectionGuid = jsonNode1.get("data").get("section").get("guid").asText();
                System.out.println("guid: " + sectionGuid);
            }
        } catch (JsonProcessingException e) {
            log.info("解析创建分组返回json报错: {}", createTaskResponse);
        }
        System.out.println(taskListGuid + ":" + sectionGuid);
        lambdaUpdateWrapper.clear();
        lambdaUpdateWrapper.eq(EcoCompanyWebMappingEntity::getAccount, ecoCompanyWebMappingEntity.getAccount())
                .eq(EcoCompanyWebMappingEntity::getId, ecoCompanyWebMappingEntity.getId())
                .eq(EcoCompanyWebMappingEntity::getPrincipalName, ecoCompanyWebMappingEntity.getPrincipalName())
                .eq(EcoCompanyWebMappingEntity::getPrinciPhone, ecoCompanyWebMappingEntity.getPrinciPhone())
                .eq(EcoCompanyWebMappingEntity::getCompanyName, ecoCompanyWebMappingEntity.getCompanyName())
                .eq(EcoCompanyWebMappingEntity::getCompanyAbbreviation, ecoCompanyWebMappingEntity.getCompanyAbbreviation())
                .eq(EcoCompanyWebMappingEntity::getWebHook, ecoCompanyWebMappingEntity.getWebHook())
                .eq(EcoCompanyWebMappingEntity::getTaskMonitorUrl, ecoCompanyWebMappingEntity.getTaskMonitorUrl())
                .set(EcoCompanyWebMappingEntity::getTasklistId, taskListGuid)
                .set(EcoCompanyWebMappingEntity::getSectionId, sectionGuid);
        ecoCompanyWebMappingEntityService.update(lambdaUpdateWrapper);
        return taskListGuid + ":" + sectionGuid;
    }
}
